import { message } from 'antd';
import axios from 'axios';
/**
 * 请求拦截器
 * 处理http请求request，添加token等
 */

const request = axios.create({
  withCredentials: true,
  // timeout: 60000,
  baseURL: '/api',
});

request.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token');
    config.headers['authorization'] = `Bearer ${token}`;
    return config;
  },
  error => {
    return Promise.reject(error);
  },
);

/**
 * 响应拦截器
 * 处理http响应response，判断异常或错误等
 */
request.interceptors.response.use(
  response => {
    if (response.status === 200) {
      if (response.config.responseType === 'blob') {
        return Promise.resolve(response.data);
      }
      if (response.data.code === 401) {
        message.error('请重新登录');
        return Promise.reject(response.data);
      }
      if (response.data.code !== 200) {
        message.error(response.data.message || '请求失败');
        return Promise.reject(response.data);
      }
      const data = response.data;
      return Promise.resolve(data);
    } else {
      return Promise.reject(response.data);
    }
  },
  error => {
    message.error(error.message);
    return Promise.reject(error);
  },
);
export default request;
